package com.imooc.business.core.executor.collect;

import com.imooc.business.domain.Collect;
import com.imooc.business.domain.Rule;
import com.imooc.business.util.DateUtil;
import com.imooc.infra.repository.jdbc.params.StandardSqlParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Slf4j
public abstract class AbstractCollectProcess implements CollectProcess {
    /**
     * 校验采集模型是否存在
     * @param rule
     * @return
     */
    protected boolean checkCollect(Rule rule) {
        List<Collect> collects = rule.getCollects();
        if (CollectionUtils.isEmpty(collects)) {
            log.error("采集模型数据不存在");
            return false;
        }
        return true;
    }

    /**
     * 如果指标全部都是0， 那么不入库
     * @param results
     * @param collects
     * @return
     */
    protected List<Map<String, Object>> filter(List<Map<String, Object>> results, List<Collect> collects) {
        Set<String> indexNames = collects.stream().map(Collect::getEnName).collect(Collectors.toSet());
        return results.parallelStream().filter(map -> {
            boolean flag = false;
            for (String indexName: indexNames) {
                Object indexValue = map.get(indexName);
                if (Objects.nonNull(indexValue)) {
                    try {
                        double v = Double.parseDouble(indexValue.toString());
                        if (v != 0) {
                            flag = true;
                            break;
                        }
                    } catch (Exception e) {
                        flag = false;
                        log.warn("过滤未知数据, map:{}, indexName:{}, e=", map, indexName, e);
                        break;
                    }
                }
            }
            return flag;
        }).collect(Collectors.toList());
    }

    /**
     * 按照用户定义的规则格式化请求时间
     * @param params
     * @param startTime
     * @param endTime
     * @param periodFormat
     */
    protected void fomatTimeParams(Map<String, Object> params, Date startTime, Date endTime, String periodFormat) {
        params.put(StandardSqlParam.START_TIME, getFormatTime(startTime, periodFormat));
        params.put(StandardSqlParam.END_TIME, getFormatTime(endTime, periodFormat));
    }

    protected Object getFormatTime(Date time, String periodFormat) {
        if (StringUtils.isEmpty(periodFormat)) {
            return time;
        }
        return DateUtil.formatDate(time, periodFormat);
    }
}
